// src/util/genericApi.js
import axios from "axios";
import { getJwt, removeJwt } from "@/api/jwt.js";

class GenericApi {
    constructor() {
        // 创建axios实例
        this.instance = axios.create({
            timeout: 3000
        });

        // 响应拦截器
        this.instance.interceptors.response.use(
            response => {
                console.log(response);
                return response.data;
            },
            error => {
                if (error.response?.status === 401) {
                    removeJwt();
                    location.href = "/login";
                }
                return Promise.reject(error.response?.data || error);
            }
        );

        // 请求拦截器
        this.instance.interceptors.request.use(
            config => {
                config.headers["Authorization"] = getJwt();
                return config;
            },
            error => {
                return Promise.reject(error);
            }
        );
    }

    // 通用请求方法
    request(service, endpoint, options = {}) {
        return this.instance({
            baseURL: `/${service}`,
            url: endpoint,
            ...options
        });
    }

    // GET请求
    get(service, endpoint, params = {}) {
        return this.request(service, endpoint, {
            method: 'GET',
            params
        });
    }

    // POST请求
    post(service, endpoint, data = {}) {
        return this.request(service, endpoint, {
            method: 'POST',
            data
        });
    }

    // PUT请求
    put(service, endpoint, data = {}) {
        return this.request(service, endpoint, {
            method: 'PUT',
            data
        });
    }

    // DELETE请求
    // DELETE请求 - 支持传递请求体
    delete(service, endpoint, params = {}, data = null) {
        const config = {
            method: 'DELETE',
            params
        };
        // 如果提供了请求体数据，则添加到配置中
        if (data !== null) {
            config.data = data;
        }

        return this.request(service, endpoint, config);
    }

}

export default new GenericApi();
